package com.shatower.chatctrl.controller;

import com.alibaba.fastjson.JSON;
import com.shatower.chatctrl.dao.pojo.*;
import com.shatower.chatctrl.dao.pojo.Groups;
import com.shatower.chatctrl.dao.service.*;
import com.shatower.chatctrl.result.*;
import com.shatower.chatctrl.utils.EmojiFilter;
import com.shatower.chatctrl.utils.RedisSource;
import com.shatower.chatctrl.utils.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hhggccll on 2017/10/15.
 */
@Controller
@RequestMapping("/uplink")
public class UplinkController extends  BaseController {

    private static Logger logger = LoggerFactory.getLogger(UplinkController.class);
    @Autowired
    private MemberService  memberService;

    @Autowired
    private GroupsService groupsService;

    @Autowired
    private UserService userService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private RedisSource redisSource;

    @Autowired
    private FriendService friendService;

    @Autowired
    private CircleService circleService;

    @Autowired
    private  VolunteerService volunteerService;

    @RequestMapping("syncgroup")
    @ResponseBody
    public Object syncgroup(GroupSync groupSync) throws IOException {
        Result res = new Result();
        String curWeixinId = groupSync.getCurWeixinID();
        List<GroupInfo> lst = groupSync.getGroupList();

        if(lst==null ||lst.size()==0){
            res.setMsg("Group List is empty");
            res.setCode(Short.valueOf("1"));
            logger.debug("weixiId "+curWeixinId+" Group List is empty");
            return res;
        }
        Groups group = new Groups();
        Date now = new Date();
        String pattern = "^.*?\\((\\d+)月(\\d+)日前";
        Pattern r = Pattern.compile(pattern);
        for(GroupInfo gi: lst){
            group.setAdminweixinid(gi.getRoomowner());

            group.setGroupname(gi.getNickname());
            group.setWeixingroupid(gi.getUsername());

            String desc = gi.getQrcodeDesc();
            String qrcode = gi.getQrcode();
            if(qrcode != null && qrcode.length()>1000) {
                group.setErcode(gi.getQrcode().getBytes("UTF-8"));
                Matcher m = r.matcher(desc);
                if (m.find()) {
                    String month = m.group(1);
                    String day = m.group(2);
                    Calendar rightNow1 = Calendar.getInstance();
                    rightNow1.setTime(now);
                    rightNow1.set(rightNow1.get(Calendar.YEAR), Integer.valueOf(month), Integer.valueOf(day), 0, 0, 0);
                    group.setErcodeinvalidtime(rightNow1.getTime());
                }
            }
            group.setUpdatetime(now);
            int rr = groupsService.insertSelective(group);
            if(rr<1){
                res.setMsg("insert group faliure");
                res.setCode(Short.valueOf("1"));
                return res;
            }
        }
        return res;
    }


    @RequestMapping("syncmember")
    @ResponseBody
    public Object syncmember(MemberSync memberSync) throws IOException {
        Result res = new Result();
        String curWeixinId = memberSync.getCurWeixinID();
        List<MemberInfo> lst = memberSync.getGroupMemberList();
        String groupWeixinId = memberSync.getWeixinGroupId();

        if(lst == null||lst.size()==0){
            res.setMsg("Member list is empty");
            return res;
        }
        if(groupWeixinId == null){
            res.setMsg("Group Id  is empty");
            return res;
        }

        Member member = new Member();
        Date now = new Date();
        User user = new User();
        for(MemberInfo mi :lst){
            member.setUpdatetime(now);
            member.setWeixingroupid(groupWeixinId);
            member.setUserweixinid(mi.getUsername());
            member.setJointime(now);
            int r = memberService.insertSelective(member);
            if(r<1){
                res.setMsg("insert member faliure");
                logger.debug("weixiId  "+curWeixinId+" insert member faliure");
                res.setCode(Short.valueOf("1"));
                return res;
            }

            user.setUserweixinid(mi.getUsername());
            user.setUpdatetime(now);
            user.setUserweixincountry(mi.getLocInfo());
            user.setUserweixinimgurl(null);
            user.setUserweixinname(EmojiFilter.filter(mi.getAlias()));
            user.setWeixinnickname(EmojiFilter.filter(mi.getNickname()));
            user.setUserweixinprovince(mi.getProvince());
            user.setUserweixinsexy(mi.getSex());

            r = userService.insertSelective(user);
            if(r<1){
                res.setMsg("insert user faliure");
                res.setCode(Short.valueOf("1"));
                return res;
            }
        }
        return res;
    }

    @RequestMapping("upload")
    @ResponseBody
    public Object upload(RecordUpload recordUpload) throws IOException {
        Result res = new Result();
        String curWeixinId = recordUpload.getCurWeixinID();
        if(curWeixinId == null){
            res.setCode(Short.valueOf("1"));
            res.setMsg("curWeixinId is not exsit.");
            logger.debug("curWeixinId is not exsit.");
            return res;
        }
        String msg = new String();
        Volunteer volunteer = new Volunteer();
        volunteer.setUpdatetime(new Date());
        volunteer.setVolunteerweixinid(curWeixinId);
        int r = volunteerService.insertSelective(volunteer);
        if(r<1){
            res.setMsg("insert volunteer faliure");
            logger.debug("weixiId "+curWeixinId+" insert volunteer faliure");
            res.setCode(Short.valueOf("1"));
            msg = "weixiId "+curWeixinId+" insert volunteer faliure";
            return res;
        }
        List<RecordInfo> lst = recordUpload.getRecordList();
        if(lst != null) {
            Record record = new Record();
            for (RecordInfo ri : lst) {
                if(ri.getContent()==null||ri.getContent().length()>1000){
                    continue;
                }
                record.setRecordid(Long.valueOf(ri.getMsgSvrId()));
                record.setUserweixinid(ri.getGroupTalker());
                Long tt = Long.valueOf(ri.getCreateTime());
                if (tt != null) {
                    Calendar rightNow1 = Calendar.getInstance();
                    rightNow1.setTimeInMillis(tt);
                    record.setCreatedate(rightNow1.getTime());
                }
                record.setGroupweixinid(ri.getTalker());
                record.setRecordcontent(ri.getContent());
                record.setRecordtype(ri.getType());
                r = recordService.insertSelective(record);
                if (r < 0) {
                    res.setMsg("insert record faliure");
                    res.setCode(Short.valueOf("1"));
                    logger.debug("weixiId "+curWeixinId+" insert record faliure.  "+JSON.toJSONString(record));
                    msg = "weixiId "+curWeixinId+" insert record faliure.  "+JSON.toJSONString(record);
                    return res;
                }
            }
        }else{
            logger.debug("weixiId "+curWeixinId+" record List is empty");
            msg = "weixiId "+curWeixinId+" record List is empty";
        }
        Jedis jedis = null;
        String rkey = new String("cmdcmd");
        rkey+=curWeixinId;
        String value = null;
        try {
            jedis = redisSource.getConnection();
            byte[] bb = jedis.rpop(rkey.getBytes());
            value = (String)SerializeUtil.unserialize(bb);
        }catch (Exception e){
            e.printStackTrace();
            redisSource.destoryConnection(jedis);
        } finally {
            redisSource.closeConnection(jedis);
        }

        if(value == null){
            CommonHeader ch = new CommonHeader();
            ch.setCmd("idle");
            ch.setInfo(msg);
            return ch;
        }
        return JSON.parse(value);
    }
    @RequestMapping("change")
    @ResponseBody
    public Object change(ChangeSync changeSync) throws IOException {
        Result res = new Result();

        if(changeSync==null){
            logger.debug("ChangeSync is invalid");
        }
        String groupid = changeSync.getGroupWeixinId();
        List<ChangeInfo> memberInfos = changeSync.getMemberList();
        Date now = new Date();
        if(changeSync.getAction()==1){
            for(ChangeInfo ci: memberInfos){
                Member member = new Member();
                member.setUpdatetime(now);
                member.setJointime(now);
                member.setUserweixinid(ci.getUsername());
                member.setWeixingroupid(groupid);
                memberService.updateByPrimaryKeySelective(member);
            }
        }

        //System.out.println(changeSync);
        return res;
    }

    @RequestMapping("report")
    @ResponseBody
    public Object report(ReportInfo reportInfo) throws IOException {
        Result res = new Result();
        if(reportInfo.getStatus() == false) {
            logger.warn(reportInfo.getErrorMsg());
            for(String user: reportInfo.getAbnormalUser()){
                FriendKey key = new FriendKey();
                key.setFriendweixinid(user);
                key.setUserweixinid(reportInfo.getCurWeixinID());
                friendService.deleteByPrimaryKey(key);
            }
            return res;
        }
        Groups group = new Groups();
        group.setWeixingroupid(reportInfo.getGroupWeixinId());
        group.setCircleid(reportInfo.getCallbackID());
        group.setAdminweixinid(reportInfo.getCurWeixinID());
        group.setUpdatetime(new Date());
        groupsService.insertSelective(group);
        return res;
    }

    @RequestMapping("friendlist")
    @ResponseBody
    public Object friendlist(FriendInfo friendInfo) throws IOException {
        Result res = new Result();
        if(friendInfo==null){
            logger.debug(" friend list is invalid");
        }
        String curWeixinId = friendInfo.getCurWeixinID();
        List<MemberInfo> lst = friendInfo.getFriendList();
        if(lst==null || lst.size()==0){
            res.setMsg(" friend list is empty ");
            res.setCode(Short.valueOf("1"));
            logger.debug("friend list is empty");
            return res;
        }
        if(curWeixinId==null){
            res.setMsg(" curWeixinId is empty ");
            res.setCode(Short.valueOf("1"));
            logger.debug("curWeixinId is invalid");
            return res;
        }
        Date now = new Date();
        Friend  friend = new Friend();
        for(MemberInfo fi:lst){
            if(curWeixinId.equalsIgnoreCase(fi.getUsername()))
                continue;
            friend.setUpdatetime(now);
            friend.setFriendweixinid(fi.getUsername());
            friend.setUserweixinid(curWeixinId);
            friendService.insertSelective(friend);

            User user = new User();
            user.setUserweixinid(fi.getUsername());
            user.setUpdatetime(now);
            user.setUserweixincountry(fi.getLocInfo());
            user.setUserweixinimgurl(null);
            user.setUserweixinname(EmojiFilter.filter(fi.getAlias()));
            user.setWeixinnickname(EmojiFilter.filter(fi.getNickname()));
            user.setUserweixinprovince(fi.getProvince());
            user.setUserweixinsexy(fi.getSex());

            userService.insertSelective(user);
        }
        return res;
    }
}
